package com.yk.lb;

import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MyLoadBalanceImpl implements MyLoadBalance {
    AtomicInteger atomicInteger = new AtomicInteger(0);

    private final int getAndIncrement() {
        int curr = atomicInteger.get();
        int next = 0;
        do {
            next = curr >= Integer.MAX_VALUE ? 0 : curr + 1;
        } while (!atomicInteger.compareAndSet(curr, next));
        System.out.println("当前第几次访问?" + atomicInteger.get());
        return atomicInteger.get();

    }


    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        int index = getAndIncrement() % serviceInstances.size();
        return serviceInstances.get(index);
    }

}
